package com.breeze.av.audio

import android.content.ContentResolver
import android.media.Ringtone
import android.media.RingtoneManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.breeze.av.R

/**
 * 注意：
 * 1. 播放音频时测试音频可能无线循环，将Ringtone的isLooping的设置为false也不起作用，故需要即使调用stop方法停止音频播放
 * 2. 不需要权限
 */
class AudioActivity : AppCompatActivity() {
    private lateinit var mRingtone: Ringtone
    private lateinit var mSystemRingtone: Ringtone
    private lateinit var mDefaultIncomingRingtone: Ringtone
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_audio)
        initCustomAudio()
        initSystemAudio()
        initDefaultIncomingRingtone();
    }

    private fun initDefaultIncomingRingtone() {
        // 根据音频类型获取默认的额音频Uri
        val defaultIncomingRingtoneUri =
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
        mDefaultIncomingRingtone = RingtoneManager.getRingtone(this, defaultIncomingRingtoneUri)
    }

    private fun initSystemAudio() {
        val manager = RingtoneManager(this)
        val cursor = manager.cursor
        val count = cursor.count
        val position = (Math.random() * count).toInt()
        Log.i(TAG, "initSystemAudio: count=${count}, position=${position}")
        mSystemRingtone = manager.getRingtone(position)
    }

    private fun initCustomAudio() {
        // 获取自定义音频URI
        var ringtoneUri: Uri =
            Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${packageName}/${R.raw.carbon}")
        // 获取Ringtone
        mRingtone = RingtoneManager.getRingtone(this, ringtoneUri)
    }

    fun startCustomRingtone(view: View) {
        if (!mRingtone.isPlaying) {
            mRingtone.play()
        }
    }

    fun stopCustomRingtone(view: View) {
        if (mRingtone.isPlaying) {
            mRingtone.stop()
        }
    }

    fun stopSystemRingtone(view: View) {
        if (mSystemRingtone.isPlaying) {
            mSystemRingtone.stop()
        }
    }

    fun startSystemRingtone(view: View) {
        if (!mSystemRingtone.isPlaying) {
            mSystemRingtone.play()
        }
    }

    fun playDefaultIncomingRingtone(view: View) {
        if (mDefaultIncomingRingtone.isPlaying) {
            mDefaultIncomingRingtone.stop()
        } else {
            mDefaultIncomingRingtone.play()
        }
    }

    companion object {
        private const val TAG = "AudioActivity"
    }


}